package com.creditease.mobile.news.util;

import android.os.AsyncTask;
import com.creditease.mobile.news.db.DBUtils;
import com.creditease.mobile.news.db.NewsSQLiteOpenHelper;
import com.creditease.mobile.news.model.ImgModel;
import com.creditease.mobile.news.model.NewsModel;
import com.creditease.mobile.news.services.NewsServices;
import com.creditease.mobile.news.ui.NewsHomeActivity;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.util.FileUtil;
import com.creditease.mobile.vo.TopVo;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

public class NewsListDownloadTask extends AsyncTask<Object, Void, Boolean> {
    private String TAG = NewsListDownloadTask.class.getName();

    @SuppressWarnings(value = "ALL")
    @Override
    protected Boolean doInBackground(Object... objs) {
        final NewsSQLiteOpenHelper dbHelper = (NewsSQLiteOpenHelper) objs[0];
        List<TopVo> list = (List<TopVo>) objs[1];
        final NewsHomeActivity home = (NewsHomeActivity) objs[2];
        final int start = (Integer) objs[3];
        final int max = (Integer) objs[4];
        final NewsServices ns = new NewsServices();
        ExecutorService es = Executors.newFixedThreadPool(5);
        ExecutorCompletionService ess = new ExecutorCompletionService(es);

        for (final TopVo rs : list) {
            Callable callable = new Callable() {
                @Override
                public String call() throws Exception {
                    String cid = rs.cid;
                    try {
                        List<NewsModel> list2 = ns.getRemoteData(rs.cid, start, max, dbHelper);

                        dbHelper.deleImg(cid);
                        int i = 0;
                        for (NewsModel news : list2) {
                            dbHelper.insertDataToNewsListTable(cid, news.docid,
                                    news.imgsrc, news.digest, news.replyCount, news.url, news.title,
                                    news.lmodify, news.subtitle, "false", "false", news.hasImg,
                                    "false", (i++) + "", "", "");
                        }
                        home.reflushCallBack(false, "true", cid);
                    } catch (Exception e) {
                        e.printStackTrace();
                        home.reflushCallBack(false, "false", cid);
                    }
                    return cid;
                }
            };
            ess.submit(callable);
        }
        for (int i = 0; i < list.size(); i++) {

            try {
                ess.take().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        return false;
    }
}
